<%@page language="java" contentType="text/html;charset=UTF-8" %>
<%@page import="java.util.*"%>
<%@page import="weaver.file.FileUpload"%>
<%@page import="weaver.general.Util"%>
<%@page import="java.net.URLDecoder"%>
<%@page import="weaver.hrm.*" %>
<%@ page import="weaver.systeminfo.*" %>
<%@page import="weaver.conn.RecordSet" %>
<%@page import="weaver.mobile.plugin.ecology.service.HrmResourceService"%>
<%@page import="weaver.general.TimeUtil"%>
<%@page import="weaver.email.service.*"%>
<%@page import="weaver.hrm.resource.ResourceComInfo"%>
<%@page import="weaver.splitepage.transform.SptmForMail"%>
<%@page import="weaver.email.WeavermailUtil"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="net.sf.json.*"%>
<%@page import="weaver.email.WeavermailComInfo"%>
<%@ page import="weaver.email.domain.*" %>
<%@ page import="java.util.*" %>
<%@ page import="weaver.hrm.*" %>
<%@ page import="weaver.systeminfo.*" %>
<%@ page import="weaver.general.StaticObj" %>
<%@ page import="weaver.hrm.settings.RemindSettings" %>
<%@ page import="org.apache.commons.logging.Log"%>
<%@ page import="org.apache.commons.logging.LogFactory"%>
<%@ page import="weaver.docs.category.security.AclManager" %>
<%@ page import="weaver.general.GCONST"%>
<%@page import="weaver.general.AttachFileUtil"%>
<%@page import="java.text.DecimalFormat"%>
<%@page import="java.io.*"%>
<%@page import="weaver.hrm.company.DepartmentComInfo"%>
<%@page import="weaver.hrm.company.SubCompanyComInfo"%>
<%@page import="weaver.email.MailSend"%>
<%@page import="weaver.general.BaseBean"%>
<%@page import="com.weaver.formmodel.mobile.manager.MobileUserInit"%>
<%@page import="weaver.formmode.virtualform.UUIDPKVFormDataSave"%>

<jsp:useBean id="MailConfigService" class="weaver.email.service.MailConfigService" scope="page" />
<jsp:useBean id="mms" class="weaver.email.service.MailManagerService" scope="page" />
<jsp:useBean id="mrs" class="weaver.email.service.MailResourceService" scope="page" />
<jsp:useBean id="mas" class="weaver.email.service.MailAccountService" scope="page" />
<jsp:useBean id="resourceComInfo" class="weaver.hrm.resource.ResourceComInfo" scope="page" />
<jsp:useBean id="mss" class="weaver.email.service.MailSettingService" />
<jsp:useBean id="mrfs" class="weaver.email.service.MailResourceFileService" />
<jsp:useBean id="lms" class="weaver.email.service.LabelManagerService" scope="page" />
<jsp:useBean id="fms" class="weaver.email.service.FolderManagerService" scope="page" />
<jsp:useBean id="cms" class="weaver.email.service.ContactManagerService" scope="page" />
<jsp:useBean id="SptmForMail" class="weaver.splitepage.transform.SptmForMail" />
<jsp:useBean id="rs0" class="weaver.conn.RecordSet" scope="page" />
<jsp:useBean id="rst" class="weaver.conn.RecordSet" scope="page" />
<jsp:useBean id="WeavermailUtil" class="weaver.email.WeavermailUtil" scope="page" />
<jsp:useBean id="ResourceComInfo" class="weaver.hrm.resource.ResourceComInfo" scope="page"/>
<jsp:useBean id="DepartmentComInfo" class="weaver.hrm.company.DepartmentComInfo" scope="page" />
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page" />
<jsp:useBean id="RecordSet" class="weaver.conn.RecordSet" scope="page" />
<jsp:useBean id="mailSend" class="weaver.email.MailSend" scope="page" />
<jsp:useBean id="CrmShareBase" class="weaver.crm.CrmShareBase" scope="page"/>

<%

out.clearBuffer();
request.setCharacterEncoding("UTF-8");
FileUpload fu=new FileUpload(request);

HrmResourceService hrs = new HrmResourceService();
String userid = Util.null2String(fu.getParameter("userid"));
User user = hrs.getUserById(Util.getIntValue(userid));
if(user==null){
	user = MobileUserInit.getUser(request,response);
}
if(user==null) {
	Map result = new HashMap();
	//未登录或登录超时
	result.put("error", "200001");
	JSONObject jo = JSONObject.fromObject(result);
	out.println(jo);
	return;
}
String operation = Util.null2String(fu.getParameter("operation"));
String keyword = Util.null2String(fu.getParameter("keyword"));
keyword = URLDecoder.decode(keyword, "utf-8");

Map result = new HashMap();
if("getMailList".equals(operation)) {//获取邮件列表
	String mailtype = Util.null2String(fu.getParameter("mailtype"));
	String folderid = Util.null2String(fu.getParameter("folderid"));
	String labelid = Util.null2String(fu.getParameter("labelid"));
	String subject = Util.null2String(fu.getParameter("subject"));
	String star = Util.null2String(fu.getParameter("star"));
	int index = Util.getIntValue(fu.getParameter("index"),1);
	int perpage = Util.getIntValue(fu.getParameter("perpage"),20);
	int isInternal = Util.getIntValue(fu.getParameter("isInternal"),-1);
	
	String mailaccountid = Util.null2String(fu.getParameter("mailaccountid"));
	String status = Util.null2String(fu.getParameter("status"));
	String from = Util.null2String(fu.getParameter("from"));
	String to = Util.null2String(fu.getParameter("to"));
	String tohrmid = Util.null2String(fu.getParameter("tohrmid"));
	String fromhrmid = Util.null2String(fu.getParameter("fromhrmid"));
	String attachmentnumber = Util.null2String(fu.getParameter("attachmentnumber"));
	String datetype = Util.null2String(fu.getParameter("datetype"));
	String startdate = Util.null2String(fu.getParameter("startdate"));
	String enddate = Util.null2String(fu.getParameter("enddate"));
	String sortColumn = Util.null2String(fu.getParameter("sortColumn"));
	String sortType = Util.null2String(fu.getParameter("sortType"));
	String waitdeal = Util.null2String(fu.getParameter("waitdeal"));
	mrs.setResourceid(user.getUID()+"");
	mrs.setFolderid(folderid+"");
	mrs.setLabelid(labelid);
	mrs.setStarred(star);
	mrs.setWaitdealid(waitdeal);
	mrs.setSubject(subject.trim());
	mrs.setSendfrom(from);
	mrs.setSendto(to);
	mrs.setFromhrmid(fromhrmid);
	mrs.setTohrmid(tohrmid);
	mrs.setStatus(status);
	mrs.setAttachmentnumber(attachmentnumber);
	mrs.setMailaccountid(mailaccountid);
	mrs.setIsInternal(isInternal);
	mrs.setDatetype(datetype);
	mrs.setStartdate(startdate);
	mrs.setEnddate(enddate);
	mrs.setSortColumn(sortColumn);
	mrs.setSortType(sortType);
	mrs.selectMailResourceSplitePage(perpage,index);
	
	mrs.setLanguageid(user.getLanguage()); 
	
	int currentYear = new Date().getYear();
	int currentMonth = new Date().getMonth();
	int currentWeek = this.getWeekOfYear(new Date(),2);
	String currentDate = TimeUtil.getCurrentDateString();
	int currentWeekDate =TimeUtil.dateWeekday(currentDate);
	JSONArray dataArray = new JSONArray();
	int maxWeek = 55;
	if(currentMonth !=0 && currentWeek == 1){
		currentWeek = maxWeek;
	}
	
	int totalSize = 0;
	while(mrs.next()){
		totalSize ++;
		String sendDate =  mrs.getOnlySenddate();
		if(sendDate==null||sendDate.equals("")){ //如果发送日期无效就默认采用当前时间
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			sendDate=df.format(new Date());
		}		   
		int theWeek = this.getWeekOfYear(TimeUtil.getString2Date(sendDate,"yyyy'-'MM'-'dd"),2);
		int theDay = TimeUtil.dateWeekday(sendDate);
		Calendar cl =  TimeUtil.getCalendar(sendDate,"yyyy'-'MM'-'dd");
		int theYear = TimeUtil.getString2Date(sendDate,"yyyy'-'MM'-'dd").getYear();
		int theMonth = TimeUtil.getString2Date(sendDate,"yyyy'-'MM'-'dd").getMonth();
		if(theMonth !=0 && theWeek == 1){
			theWeek = maxWeek;
		}
		dataArray.add(getTableString(mrs,user,isInternal,folderid));	
		continue;
	}
	
	JSONObject resultObj = new JSONObject();
	resultObj.put("datas",dataArray.toString());
	boolean ishavaNext = false;
	if(totalSize==perpage){
		mrs.selectMailResourceSplitePage(perpage,index+1);//下一页内容
		if(mrs.next()){
			ishavaNext = true;
		}
	}
	resultObj.put("totalSize", totalSize);
	resultObj.put("ishavaNext", ishavaNext);
	response.getWriter().write(resultObj.toString());
	return;
}else if("getMailContent".equals(operation)) {//获取邮件显示数据
	
	userid=""+user.getUID();
	String useridStr = ""+user.getUID();
	int mailid = Util.getIntValue(fu.getParameter("mailid"),-1);
	int folderid = Util.getIntValue(fu.getParameter("folderid"),Integer.MIN_VALUE);
	int isInternal = Util.getIntValue(fu.getParameter("isInternal"),0);
	int star = Util.getIntValue(fu.getParameter("star"),0);
	String recallState = "";
	String isPrint = Util.null2String(fu.getParameter("isPrint"));
	//更新内部邮件: 邮件读取时间
	mrs.updateMailResourceReaddate(String.valueOf(mailid));
	//删除邮件提醒信息
	mrs.removeMailRemindInfo(mailid,user.getUID());
	//布局信息
	mss.selectMailSetting(user.getUID());
	int layout = Util.getIntValue(mss.getLayout(),3);
	SimpleDateFormat dateFormat1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
	SimpleDateFormat dateFormatlanguage = dateFormat2;
	if(user.getLanguage() == 8) {
		dateFormatlanguage = dateFormat1;
	}
	
	// 读取邮件，并加载到缓存中
	mrs.setId(mailid+"");
	mrs.selectMailResource();
	WeavermailComInfo wmc = new WeavermailComInfo();
	int isInternalT = 0;
	if(mrs.next()){
		int resourceid = Util.getIntValue(mrs.getResourceid());
		String resourceids=","+MailManagerService.getAllResourceids(""+resourceid)+",";
		if(!resourceids.contains(","+resourceid+",")){ //判断是否有权限查看邮件
			JSONObject resultObj = new JSONObject();
			resultObj.put("totalSize", 0);
			resultObj.put("msg", "无权查看该邮件");
			response.getWriter().write(resultObj.toString());
			return;
		}else{
			wmc.setPriority(mrs.getPrioority()) ;
			wmc.setRealeSendfrom(mrs.getSendfrom()) ;
			wmc.setRealeCC(mrs.getSendcc()) ;
			wmc.setRealeTO(mrs.getSendto()) ;
			wmc.setRealeBCC(mrs.getSendbcc()) ;
			wmc.setSendDate(mrs.getSenddate()) ;
			wmc.setSubject(mrs.getSubject()) ;
			wmc.setContent(mrs.getContent());
			wmc.setBccids(mrs.getBccids());
			wmc.setBccall(mrs.getBccall());
			wmc.setBccdpids(mrs.getBccdpids());
			wmc.setCcids(mrs.getCcids());
			wmc.setCcall(mrs.getCcall());
			wmc.setCcdpids(mrs.getCcdpids());
			wmc.setTodpids(mrs.getTodpids());
			wmc.setToids(mrs.getToids());
			wmc.setToall(mrs.getToall());
			wmc.setSendfrom(mrs.getSendfrom());
			isInternalT = mrs.getIsInternal();
			recallState = mrs.getRecallState();
			wmc.setContenttype(mrs.getMailtype());
			wmc.setReceiveNeedReceipt(mrs.getReceiveNeedReceipt());
			if(("1").equals(mrs.getHashtmlimage())){
			    wmc.setHtmlimage(true);
			}else{
			    wmc.setHtmlimage(false);
			}
		}
	}
	
	// 标记邮件为已读
	mrs.updateMailResourceStatus("1",mailid+"",user.getUID());
	
	//EML
	String _emlPath = Util.null2String(mrs.getEmlpath());
	String emlName = Util.null2String(mrs.getEmlname());
	String loadjquery= Util.null2String(fu.getParameter("loadjquery"));
	String emlPath = GCONST.getRootPath() + "email" + File.separatorChar + "eml" + File.separatorChar;
	File eml = new File(emlPath + emlName + ".eml");
	if(!_emlPath.equals("")) eml = new File(_emlPath);
	
	
	mrfs.selectMailResourceFileInfos(mailid+"","1");
	ArrayList filenames = new ArrayList() ;
	ArrayList filenums  = new ArrayList() ;
	ArrayList filenameencodes  = new ArrayList() ;
	int fileNum=0;
	
	int isEml = 0;
	rs.execute("select * from MailConfigureInfo");
	while(rs.next()){
		isEml = rs.getInt("isEml");
	}
	
	String showmode = "0";
	RecordSet rs2 = new RecordSet();
	rs2.executeSql("SELECT * FROM MailSetting WHERE userId="+user.getUID()+"");
	rs2.next();
	showmode = rs2.getString("showmode");
	if(showmode==null || "".equals(showmode))showmode = "0";
	
	JSONObject resultObj = new JSONObject();
	
	String editAgain = "";//再次编辑
	if(mrs.getFolderid().equals("-1")){
		editAgain = SystemEnv.getHtmlLabelName(83120, user.getLanguage());
	}
	String replayBtn = "";//回复
	String replayAllBtn = "";//回复所有
	if(Util.getIntValue(mrs.getFolderid()) >= 0){
		replayBtn = SystemEnv.getHtmlLabelName(117, user.getLanguage());
		replayAllBtn = SystemEnv.getHtmlLabelName(2053, user.getLanguage());
	}
	String forwardBtn = "";//转发
	if(Util.getIntValue(mrs.getFolderid()) >= -1){
		forwardBtn = SystemEnv.getHtmlLabelName(6011, user.getLanguage());
	}
	String recallBtn = ""; //撤回
	if(1 == isInternalT && wmc.getSendfrom().equals(user.getUID()+"") && !"1".equals(recallState)){
		recallBtn = SystemEnv.getHtmlLabelName(32025, user.getLanguage());
	}
	
	String disabled = ""; //已撤回
	if(1 == isInternalT && wmc.getSendfrom().equals(user.getUID()+"") && "1".equals(recallState)){
		disabled = SystemEnv.getHtmlLabelName(32412, user.getLanguage());
	}
	
	resultObj.put("folderid",mrs.getFolderid());
	resultObj.put("mailid",mailid);
	resultObj.put("editAgain",editAgain);
	resultObj.put("replayBtn",replayBtn);
	resultObj.put("replayAllBtn",replayAllBtn);
	resultObj.put("forwardBtn",forwardBtn);
	resultObj.put("recallBtn",recallBtn);
	resultObj.put("disabled",disabled);
	//-----说明------/email/new/MailView.jsp----243到316中的按钮代码未拿来---主要为删除、导出、标记、移动等按钮
	
	//下面为邮件显示部分
	String subject = getSubject(mrs.getSubject(),user);
	resultObj.put("subject",subject);//邮件待办
	resultObj.put("starred",mrs.getStarred());//标星
	resultObj.put("waitdeal",mrs.getWaitdeal());//邮件待办
	
	//自定义标签
	ArrayList mailLabels = lms.getMailLabels(mailid);
	JSONArray labelArr = new JSONArray();
	for(int i=0;i<mailLabels.size();i++){
		MailLabel ml = (MailLabel)mailLabels.get(i);
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("color",ml.getColor());
		jsonObj.put("name",ml.getName());
		jsonObj.put("labelid",ml.getId());
		jsonObj.put("mailid",mailid);
		labelArr.add(jsonObj);
	}
	resultObj.put("mailLabel",labelArr.toString());//标签信息数组
	resultObj.put("resourceid",mrs.getResourceid());//当前人等于发件人，可以查看日志
	resultObj.put("sendfrom",mrs.getSendfrom());//发件人
	
	
	String realName= "";
	String toName = "";
	
	String sendFrom="";
	String sendTo="";
	if(mrs.getIsInternal()==1){
		sendFrom=getHrmShowNameHref(mrs.getSendfrom());
	}else{
		sendFrom=getNameByEmail(mrs.getSendfrom(),userid);
	} 
	
	if(mrs.getIsInternal()==1){
		sendTo=getHrmShowNameHrefTOP(mrs,10,1,false,"sendToAllNameTo");
	}else{
		sendTo=getNameByEmailTOP(mrs.getSendto(),userid,"","sendToAllNameTo");
	}
	
	resultObj.put("sendfrom", sendFrom);//发件人
	resultObj.put("sendto", sendTo);//收件人
	resultObj.put("senddate", dateFormatlanguage.format(dateFormat1.parse(mrs.getSenddate())));//发送时间
	resultObj.put("fjcount", mrfs.getCount());//附件数
	String sendfromName = "";
	if(mrs.getIsInternal()==1){
		sendfromName = getHrmShowNameHref(mrs.getSendfrom());
	}else{
		sendfromName = getNameByEmail(mrs.getSendfrom(),userid);
	}
	resultObj.put("sendfromName", sendfromName);//发件人显示名称
	resultObj.put("isinternal", mrs.getIsInternal());//是否内部邮件
	int lxrid = -1;
	if(mrs.getIsInternal()!=1){//外部邮件,发件人id<0可添加到联系人
		lxrid = cms.getIdByMailAddress(mrs.getSendfrom(), user.getUID());
	}
	resultObj.put("lxrid", lxrid);
	
	String receiverHtml=""; 
	if(mrs.getIsInternal()==1){
		receiverHtml=getHrmShowNameHrefTOP(mrs,10,1,false,"sendToAllNameTo");
	}else{
		receiverHtml=getNameByEmailTOP(mrs.getSendto(),userid,"","sendToAllNameTo");
	}
	resultObj.put("receiverHtml", receiverHtml);
	
	boolean ccflag=false;//抄送
	if(mrs.getIsInternal()==1){
		if("1".equals(mrs.getCcall())){
			ccflag=true;
		}else if(!"".equals(mrs.getCcdpids())){
			ccflag=true;
		}else if(!"".equals(mrs.getCcids())){
			ccflag=true;
		}		
	}
	String csHTML = "";//抄送
	if(!mrs.getSendcc().trim().equals("")||ccflag){
		if(mrs.getIsInternal()==1){
			csHTML = getHrmShowNameHrefTOP(mrs,10,2,false,"sendCsAllNameTo");
		}else{
			csHTML = getNameByEmailTOP(mrs.getSendcc(),userid,"","sendCsAllNameTo");
		}
	}
	resultObj.put("csHTML", csHTML);
	
	//秘送
	boolean bccflag=false;
	 if(mrs.getIsInternal()==1){
		if("1".equals(mrs.getBccall())){
			bccflag=true;
		}else if(!"".equals(mrs.getBccdpids())){
			bccflag=true;
		}else if(!"".equals(mrs.getBccids())){
			bccflag=true;
		}		
	 }
	//密送人的判断
	//如果当前用户=改邮件的发送用户，就显示"密送人"
	boolean readBcc=false;
	//当前登陆者是否是邮件发送者
	boolean isSender = false;
	if((!mrs.getSendbcc().trim().equals("")&&mrs.getIsInternal()==1)||bccflag){
		//内部邮件------------------------------密送人处理-----------------------------------
		if(mrs.getSendfrom().equals(""+user.getUID())){
				isSender=true;
				readBcc=true;
		}
		String send_bcc=","+mrs.getSendbcc()+",";
		if(send_bcc.indexOf(","+user.getUID()+",")!=-1){
			readBcc=true;
		}else if("1".equals(mrs.getBccall())){
			//密送给所有人
			readBcc=true;
		}else if(!"".equals(mrs.getBccids())&&(","+mrs.getBccids()+",").indexOf(","+user.getUID()+",")!=-1){
			//密送给某些人,并且包含当前用户
			readBcc=true;
		}else if(!"".equals(mrs.getBccdpids())){
			//密送给某个部门,并且包含当前用户
			rs0.execute("select id from HrmResource where departmentid in("+mrs.getBccdpids()+") and id='"+user.getUID()+"'");
			if(rs0.next()){
				readBcc=true;
			}
		}	
		String msHTML = "";//密送人
		String bemsHTML = "";//被密送人
		if(readBcc){
			if(isSender) {
				if(mrs.getIsInternal()==1){
					msHTML = getHrmShowNameHrefTOP(mrs,10,3,false,"sendMsAllNameTo");
				}else{
					msHTML = getNameByEmailTOP(mrs.getSendbcc(),userid,"","sendMsAllNameTo");
				}
			}else {
				msHTML = SystemEnv.getHtmlLabelName(81749, user.getLanguage());
			}
		}
		resultObj.put("isSender", isSender);
		resultObj.put("msHTML", msHTML);
	}else if(!mrs.getSendbcc().trim().equals("")&&mrs.getIsInternal()!=1){
		//外部邮件------------------------------密送人处理-----------------------------------
		//得到当前用户的所有邮箱账号
		rs0.execute("SELECT accountMailAddress FROM MailAccount WHERE userId='"+user.getUID()+"'");
		while(rs0.next()){
			//判断该邮件是不是我发出的邮件
			if((mrs.getSendfrom().toLowerCase()).equals(rs0.getString("accountMailAddress").toLowerCase())){
				 readBcc=true;
				 isSender = true;
				 break;
			}
		}
		//如果是我发送的，就能看到密送人，否则不能看到密送人
		String msHTML = "";
		if(readBcc){
			if(mrs.getIsInternal()==1){
				msHTML = getHrmShowNameHrefTOP(mrs,10,3,false,"sendMsAllNameTo");
			}else{
				msHTML = getNameByEmailTOP(mrs.getSendbcc(),userid,"","sendMsAllNameTo");
			}
		}
		resultObj.put("isSender", isSender);
		resultObj.put("msHTML", msHTML);
	}
	resultObj.put("readBcc", readBcc);
	
	
	
	wmc.setTotlefile(fileNum);
	wmc.setFilenames(filenames);
	wmc.setFilenums(filenums);
	wmc.setFilenameencodes(filenameencodes);
	session.setAttribute("WeavermailComInfo", wmc);
	
	JSONArray attachArr = new JSONArray();
	while(mrfs.next()){ 
		JSONObject jsonObject = new JSONObject();
		int fileId = mrfs.getId();
		int fileSize=Util.getIntValue(mrfs.getFilesize(),0);
		String fileSizeName="";
		DecimalFormat df=new DecimalFormat("#.##");
		if(fileSize>(1024*1024))
			fileSizeName=df.format(fileSize/(1024.0*1024.0))+"M";
		else if(fileSize>1024)
			fileSizeName=df.format(fileSize/(1024.0))+"K";
		else
			fileSizeName=fileSize+"B";
		filenames.add(mrfs.getFilename()) ;
		filenums.add(fileId+"") ;
		filenameencodes.add("1") ;
		fileNum++ ; 
		String fileUrl = "/weaver/weaver.email.FileDownloadLocation?fileid="+fileId;
		String fileExtendName = mrfs.getFilename().substring(mrfs.getFilename().lastIndexOf(".")+1).toLowerCase();
		String imgSrc=AttachFileUtil.getImgStrbyExtendName(fileExtendName,16);
		
		jsonObject.put("fileId",fileId);
		jsonObject.put("fileSize",fileSize);
		jsonObject.put("fileSizeName",fileSizeName);
		jsonObject.put("filename",mrfs.getFilename());
		jsonObject.put("filenameshow",Util.toScreen(mrfs.getFilename(), user.getLanguage()));
		boolean isYl = false;
		if(checkFileType(Util.toScreen(mrfs.getFilename(), user.getLanguage()))){
			isYl = true;
		}
		jsonObject.put("isYl",isYl);
		jsonObject.put("imgSrc",imgSrc);
		attachArr.add(jsonObject);
	}
	
	
	//String mailContent= mrs.getContent();
	//if(mrs.getHashtmlimage().equals("1")){
	//	mrfs.selectMailResourceFileInfos(mailid+"","0");
	//	while(mrfs.next()){
	//		int imgId = mrfs.getId();
	//		String thecontentid = mrfs.getFilecontentid();
	//		String oldsrc = "cid:" + thecontentid ;
	//		String newsrc = "http://"+Util.getRequestHost(request)+"/weaver/weaver.email.FileDownloadLocation?fileid="+imgId;
	//		mailContent = Util.StringReplaceOnce(mailContent , oldsrc , newsrc ) ;
	//	}
	//}
	//mailContent = Util.replace(mailContent, "==br==", "\n", 0);
	//mailContent = "##$mailContentStart$##"+mailContent+"##$mailContentEnd$##";
	
	//System.out.println(mailContent.length()+"===mailContent===>"+mailContent);
	
	//resultObj.put("mailContent", mailContent);//邮件正文
	resultObj.put("attachArr", attachArr);//邮件正文
	
	resultObj.put("layout", layout);
	response.getWriter().write(resultObj.toString());
	return;
}else if("getMailContentEdit".equals(operation)){//获取邮件编辑数据
	
	int flag = Util.getIntValue(fu.getParameter("flag"));
	int mailid = Util.getIntValue(fu.getParameter("id"));
	String to = Util.null2String(fu.getParameter("to"));
	String type = Util.null2String(fu.getParameter("type"));
	String folderid ="-1";
	DepartmentComInfo departmentComInfo=new DepartmentComInfo();
	MailSend  s = new MailSend();
	String isInternal = Util.null2String(fu.getParameter("isInternal"));//1是内部邮件
	String star = Util.null2String(fu.getParameter("star"));
	//0--收件箱，1--发件箱，2--草稿箱，3--已删除，4内部邮件，5标星邮件，6我的文件夹
	
	String internalto="";
	String copyresourceids="";
	
	String subject="";
	String sendfrom ="";
	String sendto = "";
	String sendcc = "";
	String sendbcc = "";
	String mailContent="";
	String mailaccountid="";
	String priority="";//级别 3--普通，2--重要,1-低
	String toids="";          //接收人ids
    String ccids="";          //抄送人ids
    String bccids = "";      //密送人ids
    String toall="";
	String todpids="";
	String ccall = "";
	String ccdpids="";
	String bccall="";
	String bccdpids="";

	String accStr="";
	String accids ="";
	
	String Prev="";
	if(flag!=-1){
			if(flag ==1){//回复
				mms.getReplayMailInfo(mailid+"",user);
			}else if(flag==2){//回复全部
				mms.getReplayAllMailInfo(mailid+"",user);
			}else if(flag==3){//转发
				mms.getForwardMailInfo(mailid+"",user);
			}else if(flag==4||flag == 5){//草稿
				mms.getDraftMailInfo(mailid+"",user);
			}
			subject = Util.HTMLtoTxt(mms.getSubject()).replaceAll("\"", "");//主题
			sendfrom = mms.getSendfrom();//发件人
			sendto = mms.getSendto();
			sendcc = mms.getSendcc();//抄送
			sendbcc = mms.getSendbcc();//密送
			
			 toids= mms.getToids();         //接收人ids
		     ccids= mms.getCcids();             //抄送人ids
		     bccids = mms.getBccids();        //密送人ids
		     toall=mms.getToall();
		      todpids=mms.getTodpids();
			  ccall = mms.getCcall();
			  ccdpids=mms.getCcdpids();
			  bccall=mms.getBccall();
			  bccdpids=mms.getBccdpids();
			  
		   
		   	//回复
	     	if(flag ==1){
	     		toids=s.trim((","+sendto+",").replace(","+user.getUID()+",", ","));
	     		toall="";
	     		todpids="";
	     		ccids="";
	     		ccdpids="";
	     		ccall="";
	     		bccids="";
	     		bccdpids="";
	     		bccall="";
	     	}
	     	//如果是回复全部
	        if(flag==2){
	      	   toids=s.trim((","+toids+",").replace(","+user.getUID()+",", ","));
	      	   bccids="";
	     	   bccdpids="";
	     	   bccall="";
	        }
	        //转发
	     	if(flag ==3){
	     		toids="";
	     		todpids="";
	     		toall="";
	     		ccids="";
	     		ccdpids="";
	     		ccall="";
	     		bccids="";
	     		bccdpids="";
	     		bccall="";
	     	}
	     	//if(flag==4){
	     	//		String fengeinput="<br><font style=color:red>"+SystemEnv.getHtmlLabelName(81409,user.getLanguage())+"</font><span id=EmailNew_fengeinput></span><br>";
	     	//		mailContent=mms.getContent().replace(fengeinput, "");
	     	//}else{
	     	//	mailContent = mms.getContent();
	     	//}
	     		
   
			//mailContent = mms.getContent();
			priority=mms.getPriority();
			//对mailContent进行分割处理
			
			accStr = mms.getAccStr();
			accids = mms.getAccids();
			
			sendfrom = mms.getSendfrom();
	}else{
			//表示是新建邮件
			mas.clear();
			mas.setIsDefault("1");
			mas.setUserid(user.getUID()+"");
			mas.selectMailAccount();
			if(mas.next()){
				sendfrom = mas.getAccountMailAddress();
				mailaccountid = mas.getAccountid();
			}
			if(!to.equals("")){
				sendto = to;
			}
	}
			
	JSONObject resultObj = new JSONObject();
	Map mailConfig=MailConfigService.getMailConfig();
	int mailType=Util.getIntValue(Util.null2String(mailConfig.get("mailType")),0);
	boolean isHaveChecked = false;
	JSONArray mailAccountArr = new JSONArray();
	if(!("1").equals(isInternal)){//外部邮件
		mas.clear();
		mas.setUserid(user.getUID()+"");
		mas.selectMailAccount();
		while(mas.next()){
			JSONObject mailObj = new JSONObject();
			String mid = mas.getId();
			String mname = mas.getAccountname();
			boolean isselected = false;
			String tempMail = getDefaultSendFrom(mms,mas.getAccountMailAddress());
			if(!tempMail.equals("")){
				if(tempMail.equals(mas.getAccountMailAddress())){
					isselected = true;
					isHaveChecked = true;
				}
			}else{
				if(mas.getIsDefault().equals("1")&&!isHaveChecked){
					isselected = true;
					isHaveChecked = true;
				}
			}
			mailObj.put("mid",mid);
			mailObj.put("mname",mname);
			mailObj.put("isselected",isselected);
			mailAccountArr.add(mailObj);
		}
		JSONArray sendtoArr = getOutEmailShowName(sendto,user);
		JSONArray sendccArr = getOutEmailShowName(sendcc,user);
		JSONArray sendbccArr = getOutEmailShowName(sendbcc,user);
		
		resultObj.put("sendtoArr",sendtoArr);
		resultObj.put("sendccArr",sendccArr);
		resultObj.put("sendbccArr",sendbccArr);
	}
	
	if(flag == 5){
		mailid = -1;//再次编辑，产生新邮件，重置mailid值
	}
	
	
	resultObj.put("id",mailid);
	resultObj.put("isInternal",isInternal);
	resultObj.put("isHaveChecked",isHaveChecked);
	resultObj.put("mailAccountArr",mailAccountArr);
	resultObj.put("mailType",mailType);
	resultObj.put("subject",subject);
	resultObj.put("sendfrom",sendfrom);
	resultObj.put("sendto",sendto);
	resultObj.put("sendcc",sendcc);
	resultObj.put("sendbcc",sendbcc);
	
	resultObj.put("mailaccountid",mailaccountid);
	resultObj.put("priority",priority);
	
	resultObj.put("toids",toids);//接收人
	resultObj.put("toall",toall);
	resultObj.put("todpids",todpids);
	resultObj.put("toidsname",getHrmNames(toids));
	resultObj.put("todpidsname",getDeptNames(todpids));
	
	resultObj.put("ccids",ccids);//抄送人
	resultObj.put("ccall",ccall);
	resultObj.put("ccdpids",ccdpids);
	resultObj.put("ccidsname",getHrmNames(ccids));
	resultObj.put("ccdpidsname",getDeptNames(ccdpids));
	
	resultObj.put("bccids",bccids);//密送人
	resultObj.put("bccall",bccall);
	resultObj.put("bccdpids",bccdpids);
	resultObj.put("bccidsname",getHrmNames(bccids));
	resultObj.put("bccdpidsname",getDeptNames(bccdpids));
	
	
	resultObj.put("accStr",accStr);//附件
	resultObj.put("accids",accids);
	resultObj.put("Prev",Prev);
	
	response.getWriter().write(resultObj.toString());
	return;
	
}else if("recall".equals(operation)){//撤回
	String mailId = Util.null2String(fu.getParameter("mailId"));
	String flag = "true";
	try{
		//update MailResource
		String sb = SystemEnv.getHtmlLabelName(32063, user.getLanguage());
		String ct = SystemEnv.getHtmlLabelName(32064, user.getLanguage());
		String sql = "";
		if(rs.getDBType().equals("oracle")){
			sql = "update MailResource set subject =concat('"+sb+":',subject) "+
			" , content = '"+ct+"' , attachmentNumber = 0 where originalMailId ="+mailId+
			" AND id NOT IN(SELECT id FROM MailResource WHERE subject LIKE '%"+sb+":%')";
			rs.execute("update mailcontent set mailcontent = '"+ct+"' where mailid in (select id from mailresource where originalMailId = "+mailId+")");
		}else{
			sql = "update MailResource set subject ='"+sb+":'+subject "+
			" , content = '"+ct+"' , attachmentNumber = 0 where originalMailId ="+mailId+
			" AND id NOT IN(SELECT id FROM MailResource WHERE subject LIKE '%"+sb+":%')";
		}
		
		rs.execute(sql);
		sql = "DELETE FROM MailResourceFile WHERE mailid IN "+
			"(SELECT id FROM MailResource  WHERE originalMailId = "+mailId+" )";
		rs.execute(sql);
		
		//update mailresource recallstate
		sql = "update MailResource set recallState = 1 where id ="+mailId;
		rs.execute(sql);
		
		rs.execute("select subject from MailResource where id = "+mailId);
		rs.next();
		
		int totalsize = (rs.getString("subject")+sb).getBytes().length+ct.getBytes().length;
		sql = "UPDATE MailResource SET size_n = '"+totalsize+"' WHERE originalMailId = '"+mailId+"'";
		rs.execute(sql);
		
		rs.execute("select resourceid from MailResource where originalMailId = "+mailId);
		RecordSet childSet = new RecordSet();
		while(rs.next()){
			sql = "UPDATE HrmResource SET occupySpace = " +
					" round((select sum(size_n) from MailResource where resourceid = "+rs.getString("resourceid")+" and canview=1)/(1024*1024),2)" +
							" WHERE id = "+rs.getString("resourceid");
			childSet.execute(sql);
		}
	}catch(Exception e){
		flag = "false";
		new BaseBean().writeLog(e);
	}
	JSONObject resultObj = new JSONObject();
	resultObj.put("flag",flag);
	response.getWriter().write(resultObj.toString());
	return;
}else if("getEmailLxr".equals(operation)){//联系人快捷搜索
	out.clearBuffer();
	String q = Util.null2String(fu.getParameter("q")) ;
	JSONArray jsonArray = new JSONArray();
	int row = 0;
	if(!"".equals(q)){
		q=java.net.URLDecoder.decode(q,"UTF-8");
		String sqlWhere = "mailaddress like '%"+q+"%' or mailUserName like '%"+q+"%'";
		ArrayList<MailContact> list = cms.getBySql(user.getUID(), sqlWhere);
		String returnStr="";
		for(int i=0;i<list.size()&&row<5;i++){
			JSONObject jsonObject = new JSONObject();
			MailContact mc = list.get(i);
			jsonObject.put("name",mc.getMailUserName());
			jsonObject.put("to",mc.getMailAddress());
			jsonArray.add(jsonObject);
			row++;
		}
		
		if(row<5){
			StringBuffer sql = new StringBuffer();
			sqlWhere = " #### like '%" + q + "%'";
			sql.append("select id,lastname as name,email from HrmResource where (status =0 or status = 1 or status = 2 or status = 3) and email is not null and ("+sqlWhere.replaceAll("####","lastname")+" or "+sqlWhere.replaceAll("####","pinyinlastname")+" or "+sqlWhere.replaceAll("####","email")+") ");
			sql.append(" union ");
			String condition = "";
			//找到用户能看到的所有客户
			//如果属于总部级的CRM管理员角色，则能查看到所有客户。
			rs.executeSql("select id from HrmRoleMembers where  roleid = 8 and rolelevel = 2 and resourceid = " + user.getUID());
			if (rs.next()) {
				sql.append("select id,name,email from CRM_CustomerInfo where (deleted=0 or deleted is null) and  email is not null and ("+sqlWhere.replaceAll("####","name")+" or "+sqlWhere.replaceAll("####","email")+") ");
			} else {
				String leftjointable = CrmShareBase.getTempTable(user.getUID()+"");
				sql.append("select  t1.id,t1.name,t1.email "
					+ " from CRM_CustomerInfo t1 left join " + leftjointable + " t2 on t1.id = t2.relateditemid "
					+ " where t1.id = t2.relateditemid and (t1.deleted=0 or t1.deleted is null) and t1.email is not null and "+sqlWhere.replaceAll("####","t1.name")+" ");
			}
			String  json = "";
			rs.executeSql(sql.toString());
			if(rs.getCounts()>0){
				while(rs.next()&&row<5){
					json += "{to:'"+rs.getString(3)+"',name:'"+rs.getString(2)+"'";
					json += "},";
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("name",rs.getString(2));
					jsonObject.put("to",rs.getString(3));
					jsonArray.add(jsonObject);
					row++;
				}
			}
		}
	}
	JSONObject resultObj = new JSONObject();
	resultObj.put("dataArr",jsonArray);
	response.getWriter().write(resultObj.toString());
	return;
}else if("getMyContactList".equals(operation)){//获取联系人列表
	int pageNo = Util.getIntValue(Util.null2String(fu.getParameter("pageNo")),1) ;
	int pageSize = Util.getIntValue(Util.null2String(fu.getParameter("pageSize")),10) ;
	keyword = Util.null2String(fu.getParameter("keyword")) ;
	String sqlwhere = " and a.userId="+user.getUID();
	if(!"".equals(keyword)){
		sqlwhere += " and mailUserName like '%"+keyword+"%' ";
	}
	String countSql = "select count(1) from MailUserAddress a where 1=1 "+sqlwhere;
	int recordCount=0;
	rs.executeSql(countSql);
	if(rs.next()){
		recordCount = rs.getInt(1);
	}
	String querysql = "select a.id, a.mailUserName, a.mailaddress, a.mailUserMobileP from MailUserAddress a where 1=1 "+sqlwhere;
	String orderby = " order by id desc ";
	String selSql = getPageSql(querysql,orderby,pageNo,pageSize);
	rs.executeSql(selSql);
    JSONArray jsonArray = new JSONArray();
    while(rs.next()){
    	JSONObject jsonObject = new JSONObject();
    	jsonObject.put("id",Util.null2String(rs.getString("id")));
    	String mailUserName = Util.null2String(rs.getString("mailUserName"));
    	String firstname = "";
    	if(!"".equals(mailUserName)&&mailUserName.length()>0){
    		firstname = mailUserName.substring(0,1);
    	}
    	jsonObject.put("mailUserName",mailUserName);
    	jsonObject.put("firstname",firstname);
    	jsonObject.put("mailaddress",Util.null2String(rs.getString("mailaddress")));
    	jsonArray.add(jsonObject);
    }
	JSONObject resultObj = new JSONObject();
	resultObj.put("totalSize", recordCount);
	resultObj.put("datas", jsonArray.toString());
	response.getWriter().write(resultObj.toString());
	return;
}else if("moveto".equals(operation)){
	String mailId = Util.null2String(request.getParameter("mailId"));
	String movetoFolder = Util.null2String(request.getParameter("movetoFolder"));
	mrs.moveMailToFolder(mailId, movetoFolder);
	JSONObject resultObj = new JSONObject();
	resultObj.put("s",1);
	response.getWriter().write(resultObj.toString());
	return;
}else if("updateStatus".equals(operation)){
	String mailId = Util.null2String(request.getParameter("mailId"));
	String status = Util.null2String(request.getParameter("status"));
	mrs.updateMailResourceStatus(status,mailId,user.getUID());
	if("1".equals(status)){
		mrs.updateMailResourceReaddate(mailId);
	}
	JSONObject resultObj = new JSONObject();
	resultObj.put("s",1);
	response.getWriter().write(resultObj.toString());
	return;
}else if("updateStar".equals(operation)){
	String mailId = Util.null2String(request.getParameter("mailId"));
	String star = Util.null2String(request.getParameter("star"));
	mrs.updateStar(mailId, star);
	JSONObject resultObj = new JSONObject();
	resultObj.put("s",1);
	response.getWriter().write(resultObj.toString());
	return;
}else if("delete".equals(operation)){
	String mailId = Util.null2String(request.getParameter("mailId"));
	String emlPath=application.getRealPath("")+"email\\eml\\";
	 mrs.deleteMail(mailId,user.getUID(),emlPath);
	JSONObject resultObj = new JSONObject();
	resultObj.put("s",1);
	response.getWriter().write(resultObj.toString());
	return;
}else if("getUUID".equals(operation)){
	UUIDPKVFormDataSave uuidpkvFormDataSave = new UUIDPKVFormDataSave();
	String uuid = uuidpkvFormDataSave.generateID(null)+"";
	JSONObject resultObj = new JSONObject();
	resultObj.put("uuid",uuid);
	response.getWriter().write(resultObj.toString());
	return;
}else if("getAutoReceiveEmail".equals(operation)){
	UUIDPKVFormDataSave uuidpkvFormDataSave = new UUIDPKVFormDataSave();
	String uuid = uuidpkvFormDataSave.generateID(null)+"";
	JSONObject resultObj = new JSONObject();
	resultObj.put("uuid",uuid);
	response.getWriter().write(resultObj.toString());
	return;
}


%>


<%!

public String getHrmNames(String ids){
	String names = "";
	try{
		ResourceComInfo ResourceComInfo = new ResourceComInfo();
		String szto[]=ids.split(",");
		for(int i=0;i<szto.length;i++){
			if(!"".equals(szto[i])){
				names +=","+ ResourceComInfo.getLastname(szto[i]);
			}
		}
		if(names.startsWith(",")){
			names = names.substring(1);
		}
	}catch(Exception e){
		e.printStackTrace();
	}
	return names;
}

public String getDeptNames(String ids){
	String names = "";
	try{
		DepartmentComInfo departmentComInfo = new DepartmentComInfo();
		String szto[]=ids.split(",");
		for(int i=0;i<szto.length;i++){
			if(!"".equals(szto[i])){
				names +=","+ departmentComInfo.getDepartmentname(szto[i]);
			}
		}
		if(names.startsWith(",")){
			names = names.substring(1);
		}
	}catch(Exception e){
		e.printStackTrace();
	}
	return names;
}

public JSONObject getTableString(MailResourceService mrs ,User user,int isInternal,String folderid) throws Exception{
	MailSettingService mailSettingService = new MailSettingService();
	mailSettingService.selectMailSetting(user.getUID());
	int userLayout = Util.getIntValue(mailSettingService.getLayout(),0);
	ResourceComInfo resourceComInfo=new ResourceComInfo();
	String userid=user.getUID()+"";
	JSONObject jsonObject = new JSONObject();
	jsonObject.put("id",mrs.getId());
	jsonObject.put("status",mrs.getStatus());
	jsonObject.put("sendfrom",mrs.getSendfrom());
	jsonObject.put("starred",mrs.getStarred());
	jsonObject.put("prioority",mrs.getPrioority());
	String prioorityLabel = "";
	if("1".equals(mrs.getPrioority())) {
		prioorityLabel = SystemEnv.getHtmlLabelName(2087,user.getLanguage());
	}
	jsonObject.put("prioorityLabel",prioorityLabel);
	jsonObject.put("folderid",mrs.getFolderid());
	jsonObject.put("timingdate",mrs.getTimingdate());
	jsonObject.put("timingdatestate",mrs.getTimingdatestate());
	jsonObject.put("attachmentnumber",mrs.getAttachmentnumber());
	//jsonObject.put("flag",mrs.getFlag());
	
	String str="";
	String timingdateLabel = "";
	String timingdateClass = "";
	
	if(mrs.getStatus().equals("1")){
		timingdateClass = "Rr";
		timingdateLabel = SystemEnv.getHtmlLabelName(25425,user.getLanguage());
	}else{
		timingdateClass = "Ru";
		timingdateLabel = SystemEnv.getHtmlLabelName(25426,user.getLanguage());
	}
	jsonObject.put("timingdateLabel",timingdateLabel);
	jsonObject.put("timingdateClass",timingdateClass);
	jsonObject.put("attachmentnumber",mrs.getAttachmentnumber());
	
	String attachmentnumberLabel = "";
	if(!mrs.getAttachmentnumber().equals("0")){
		attachmentnumberLabel = SystemEnv.getHtmlLabelName(156,user.getLanguage());
	}
	jsonObject.put("attachmentnumberLabel",attachmentnumberLabel);
	
	SptmForMail spm = new SptmForMail();	
	String realName=folderid.equals("-1")||folderid.equals("-2")?spm.getMailSendToRealName(mrs,userid):spm.getMailSendFromRealName(mrs.getSendfrom(),userid,mrs.getIsInternal());
	String title = folderid.equals("-1")||folderid.equals("-2")?realName:(mrs.getIsInternal()==1?resourceComInfo.getLastname(mrs.getSendfrom()):mrs.getSendfrom());
	
	if(1 == isInternal && !folderid.equals("-1") && !folderid.equals("-2")){
		realName = spm.getMailSendFromRealName(mrs.getSendfrom(),userid,mrs.getIsInternal());
		title = resourceComInfo.getLastname(mrs.getSendfrom());
	}
	String titleclass = "";
	String re1l = "";
	WeavermailUtil weavermailUtil = new WeavermailUtil();
	if(mrs.getIsInternal() != 1) {
		re1l = weavermailUtil.getEmailRealName(mrs.getSendfrom(),userid,true);
		titleclass = "mailaddresstitle";
	}
	
	jsonObject.put("titleclass",titleclass);
	jsonObject.put("re1l",re1l);
	jsonObject.put("isinternal",mrs.getIsInternal());
	jsonObject.put("title",title);
	jsonObject.put("realname",realName);
	jsonObject.put("userlayout",userLayout);
	jsonObject.put("subject",mrs.getSubject());
	jsonObject.put("isinternal",mrs.getIsInternal());
	jsonObject.put("subjectshow",getSubject(mrs.getSubject(),user));
			
	LabelManagerService lms = new LabelManagerService();
	int mailId = Util.getIntValue(mrs.getId());
	ArrayList mailLabels = lms.getMailLabels(mailId);
	
	JSONArray jsonArray = new JSONArray();
	String labelStr = "";
	for(int i=0;i<mailLabels.size();i++){
		MailLabel ml = (MailLabel)mailLabels.get(i);
		JSONObject mailObj = new JSONObject();
		mailObj.put("color",ml.getColor());
		mailObj.put("name",ml.getName());
		mailObj.put("labelid",ml.getId());
		mailObj.put("mailId",mailId);
		mailObj.put("title",SystemEnv.getHtmlLabelName(81338,user.getLanguage()));
		jsonArray.add(mailObj);
	}
	jsonObject.put("labelArray",jsonArray);
	jsonObject.put("waitdeal",mrs.getWaitdeal());
	jsonObject.put("waitdealtime",mrs.getWaitdealtime());
	jsonObject.put("waitdealway",mrs.getWaitdealway());
	jsonObject.put("waitdealnote",mrs.getWaitdealnote());
	jsonObject.put("wdremindtime",mrs.getWdremindtime());
	jsonObject.put("formatesenddate",getFormateSenddate(mrs,user));
	return jsonObject;
}		

public String getSubject(String subject ,User user){
	subject=subject.replaceAll("(\r\n|\r|\n|\n\r)",""); //替换换行符
	if(subject.equals("")){
		return "("+SystemEnv.getHtmlLabelName(31240,user.getLanguage())+")";
	}else{
		return subject;
	}
}

public static int getWeekOfYear(Date date, int firstDay) {
     Calendar c = new GregorianCalendar();
     c.setFirstDayOfWeek(firstDay);
     c.setTime (date);

     return c.get(Calendar.WEEK_OF_YEAR);
}

public String getFormateSenddate(MailResourceService mrs,User user) {
	
	SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm");
	SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
	String today=TimeUtil.getCurrentDateString();
	String sendtime=Util.null2String(mrs.getSenddate());
	String senddate=sendtime;
	String senddatestr="";
	try{
	String formateTime=dateFormat2.format(dateFormat.parse(sendtime));	
	if(sendtime.length()>10){
		senddate=sendtime.substring(0,10);
		if(today.equals(senddate)){
			senddate=SystemEnv.getHtmlLabelName(15537, user.getLanguage())+" "+sendtime.substring(11, 16);
		}
	}
	senddatestr=senddate;
	}catch (Exception e) {
		e.printStackTrace();
	}
	
	return senddatestr;
}

public boolean checkFileType(String filename) {
	boolean isavailable = false;
	String[] filePostfixs = {".pdf",".txt", ".png", ".doc", ".docx", ".xls", ".xlsx", ".jpg", ".bmp", ".gif"};
	if("".equals(filename) || filename == null )
		return isavailable;
		
	for(int i=0; i< filePostfixs.length; i++) {
		int index = filename.toLowerCase().lastIndexOf(filePostfixs[i]);
		if((index+(filePostfixs[i].length())) == filename.length()) { //判断文件名后缀是否以数组中的任意值结尾
			isavailable = true;
			break;		
		}  
	}
	
	return  isavailable;
}


public String getHrmShowNameHrefTOP(MailResourceService mms,int top,int type,boolean ismobile,String toWho) throws Exception {
	ResourceComInfo hrm = new ResourceComInfo();
	String all=mms.getToall();
	String dpids=mms.getTodpids();
	String ids=mms.getToids();
	String showname = "";
	if(type==2){
		 all=mms.getCcall();
		 dpids=mms.getCcdpids();
		 ids=mms.getCcids();
	}else if(type==3){
		 all=mms.getBccall();
		 dpids=mms.getBccdpids();
		 ids=mms.getBccids();
		 //1340
	}
	String allname = "";
	if("1".equals(all)){
		showname+="所有人";
		return showname;
	}else{
		DepartmentComInfo departmentComInfo=new DepartmentComInfo();
		SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
		String dep_ids[] = Util.TokenizerString2(dpids, ",");
		for(int i=0;i<dep_ids.length;i++){
            String hrmid = Util.null2String(dep_ids[i]);
            if(!hrmid.equals("")){
                if(i<top){
                    if(ismobile){
                        showname+=departmentComInfo.getDepartmentname(hrmid)+"&nbsp";
                    }else{
                        showname+=departmentComInfo.getDepartmentname(hrmid)+"&nbsp;&nbsp;";
                    }
                    allname = showname;
                }else{
                    if(ismobile){
                        allname+=departmentComInfo.getDepartmentname(hrmid)+"&nbsp";
                    }else{
                        allname+=departmentComInfo.getDepartmentname(hrmid)+"&nbsp;&nbsp;";
                    }
                }
            }
        }            
		String hrmids[] = Util.TokenizerString2(ids, ",");
        for(int i=0;i<hrmids.length;i++){
        	String hrmid = Util.null2String(hrmids[i]);
        	if(!hrmid.equals("")){
                if(i<top){
                    if(ismobile){
                        showname+=hrm.getResourcename(hrmid)+"&nbsp";
                    }else{
                        showname+=hrm.getResourcename(hrmid)+"&nbsp;&nbsp;";
                    }
                    allname = showname;
                }else{
                    if(ismobile){
                        allname+=hrm.getResourcename(hrmid)+"&nbsp";
                    }else{
                        allname+=hrm.getResourcename(hrmid)+"&nbsp;&nbsp;";
                    }
                }
                
            }
        }
        if(hrmids.length>top){
        	showname+="<span class='showAll' style='color:#0161c9;' onclick='showAllSendTo(this,\""+toWho+"\");'>[显示全部]<span id='"+toWho+"' style='display:none'>"+allname+"<span/><span/>";
        		//showname+="[显示全部]";
        }
	}
	
	return showname;
}

//得到邮件的发件人
public String getNameByEmailTOP(String mailAddress,String userid,String flag,String toWho) throws Exception{
	ResourceComInfo hrm = new ResourceComInfo();
	WeavermailUtil weavermailUtil=new WeavermailUtil();
	String result_str="";
	String temp_address[]=mailAddress.split(",");
	String allname = "";
	if(null!=temp_address){
		for(int i=0;i<temp_address.length;i++){
            String mail_adr=temp_address[i];
            if(mail_adr.equals("")) continue;
            allname+=weavermailUtil.getEmailRealName(mail_adr,userid,false)+", ";
        }
        allname = allname.substring(0,allname.length()-2);
		for(int i=0;i<temp_address.length;i++){
			String mail_adr=temp_address[i];
			if(mail_adr.equals("")) continue;
			result_str+=weavermailUtil.getEmailRealName(mail_adr,userid,false)+",";
			if(i>=4&&!flag.equals("all")){
				//result_str+="[显示全部]";
				result_str = result_str.substring(0,result_str.length()-2);
				result_str+="<span class='showAll' style='color:#0161c9;' onclick='showAllSendTo(this,\""+toWho+"\");'>[显示全部]<span id='"+toWho+"' style='display:none'>"+allname+"<span/><span/>";
				break;
			} 
		}
	}
	return result_str;
}

public String getHrmShowNameHref(String resourceids) throws Exception{
	ResourceComInfo hrm = new ResourceComInfo();
	String showname = "";
	String hrmids[] = Util.TokenizerString2(resourceids, ",");
    for(int i=0;i<hrmids.length;i++){
    	String hrmid = Util.null2String(hrmids[i]);
    	if(!hrmid.equals("")){
    		showname+=hrm.getResourcename(hrmid)+"&nbsp";
    	}
    }
	return showname;
}

public String getNameByEmail(String mailAddress,String userid) throws Exception{
	return getNameByEmailTOP(mailAddress,userid,"all","");
}


public String getDefaultSendFrom(MailManagerService mms,String accountMail){
	if(mms.getTagvalues().indexOf(accountMail.toLowerCase())>-1){
		return accountMail;
	}
	if(mms.getSendcc().toLowerCase().indexOf(accountMail.toLowerCase())>-1){
		return accountMail;
	}
	if(mms.getSendbcc().toLowerCase().indexOf(accountMail.toLowerCase())>-1){
		return accountMail;
	}
	return "";

}


public JSONArray getOutEmailShowName(String emails,User user){
	ArrayList checklist=new ArrayList();
    SptmForMail sm=new SptmForMail();
    WeavermailUtil weavermailUtil=new WeavermailUtil();
	String emails_sz[]=emails.split(",");
	String userid = user.getUID()+"";
	JSONArray jsonArray = new JSONArray();
	for(int i=0;i<emails_sz.length;i++){
		if(!"".equals(emails_sz[i])){
			JSONObject jsonObject = new JSONObject();
			String mailAddress = emails_sz[i];
			String realname = weavermailUtil.getEmailRealName(mailAddress,userid,false);
			if("".equals(realname) || mailAddress.equals(realname)){
				mailAddress = sm.getHrmResourceName(mailAddress);
			}else{
				mailAddress = realname +"&lt;"+mailAddress+"&gt;";
			}
			String jieshou=mailAddress;
			if(null!=jieshou&&!"".equals(jieshou)){
				jieshou.replace("&gt;", ">").replace("&lt;", "<");
			}
			if(checklist.contains(jieshou)==false){
				checklist.add(jieshou);
				String temp_sz=jieshou+";";
				jsonObject.put("name",emails_sz[i]);
				jsonObject.put("showname",jieshou);
				jsonArray.add(jsonObject);
			}
		}
	}
	return jsonArray;
}

/*
*传入sql  
*页数  
*每页条数
*/
public String getPageSql(String querysql,String orderby,int pageNo,int pageSize){
	RecordSet rs = new RecordSet();
	int pagesize = pageSize;
	int iNextNum = pageNo * pageSize;
	String sql = "";
	if(rs.getDBType().equals("oracle")){
		sql = "select rownum rownum_,t1.* from(" + querysql + " "+orderby+" nulls last) t1 ";
		sql = "select * from ("+sql+") t12 where rownum_ > " + (iNextNum - pagesize) + " and rownum_ <= " + iNextNum;
	}else{
		sql = "select ROW_NUMBER() OVER ("+orderby+") AS rownum_,* from (" + querysql + ") t1 ";
		sql = "select * from (" + sql + ") t12 where rownum_> " + (iNextNum - pagesize) + " and rownum_ <= " + iNextNum;
	}
	 return sql;
}
%>